//
//  ModelTool.swift
//  SwiftUIDemo
//
//  Created by zhouzuosong on 2021/2/6.
//  Copyright © 2021 Kael. All rights reserved.
//

import Foundation

// MARK: 字典转字符串
extension Dictionary {
    
    func toJsonString() -> String? {
        guard let data = try? JSONSerialization.data(withJSONObject: self,
                                                     options: []) else {
            return nil
        }
        guard let str = String(data: data, encoding: .utf8) else {
            return nil
        }
        return str
     }
    
}

// MARK: 字符串转字典
extension String {
    
    func toDictionary() -> [String : Any] {
        
        var result = [String : Any]()
        guard !self.isEmpty else { return result }
        
        guard let dataSelf = self.data(using: .utf8) else {
            return result
        }
        
        if let dic = try? JSONSerialization.jsonObject(with: dataSelf,
                           options: .mutableContainers) as? [String : Any] {
            result = dic
        }
        return result
    
    }
    
}

extension Encodable {
    subscript(key: String) -> Any? {
        return dictionary[key]
    }
    var jsonData: Data? {
        return try? JSONEncoder().encode(self)
    }
    var dictionary: [String: Any] {
        guard let data = jsonData else {return [:]}
        return (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:]
    }
    var jsonStr: String? {
        guard let data = jsonData else {return nil}
        return String(data: data, encoding: .utf8)
    }
}

extension Decodable {
    static func getModel(data: Data) -> Self? {
        return try? JSONDecoder().decode(self, from: data)
    }
    static func getModel(jsonStr: String) -> Self? {
        guard let data = jsonStr.data(using: .utf8) else {return nil}
        return try? JSONDecoder().decode(self, from: data)
    }
}
